﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.ComponentModel;
using Shoozla.DataModel;
using System.Collections.ObjectModel;
using System.Windows.Media;
using System.IO;
using System.Windows.Data;
using System.Threading.Tasks;

namespace Shoozla.ViewModel
{

    class ResultViewModel : ViewModelBase
    {

        private ICoverStorage Covers { get;  set; }

        public ListCollectionView ThumbsAlbum { get; set; }
        public ListCollectionView ThumbsSong { get; set; }
        public ListCollectionView ThumbsArtist { get; set; }
        public ListCollectionView NotFoundMp3 { get; set; }
        private Boolean _showCharts;
        public Boolean ShowCharts { get { return _showCharts; } set { _showCharts = value; OnPropertyChanged("ShowCharts"); OnPropertyChanged("ShowCover"); } }
        public Boolean ShowCover { get { return !_showCharts; }  }
            
        public ResultViewModel(ICoverStorage covers, List<Mp3File> notFoundMp3, Window view, Window owner) : base(view,owner) 
        {
            Covers = covers;
            ShowCharts = false;
            NotFoundMp3 = new ListCollectionView(notFoundMp3);
            var allThumbs = Covers.CoverThumbnails;

            List<CoverThumb> thumbsAlbumList = new List<CoverThumb>();
            List<CoverThumb> thumbsSongList = new List<CoverThumb>();
            List<CoverThumb> thumbsArtistList = new List<CoverThumb>();

            //splitting covers into 3 different lists
            foreach (CoverThumb c in allThumbs)
            {
                switch (c.Method)
                {
                    case SearchMethod.Album: { thumbsAlbumList.Add(c); break; }
                    case SearchMethod.Artist: { thumbsArtistList.Add(c); break; }
                    case SearchMethod.Song: { thumbsSongList.Add(c); break; }
                    default : { thumbsAlbumList.Add(c); break; }
                }
            }

            //settings checkbox initial status
            if (thumbsArtistList.Count > 0) AllArtistSelected = true; else AllArtistSelected = false;
            if (thumbsSongList.Count > 0) AllSongSelected = true; else AllSongSelected = false;
            if (thumbsAlbumList.Count > 0) AllAlbumSelected = true; else AllAlbumSelected = false;

            ThumbsAlbum = new ListCollectionView(thumbsAlbumList);
            ThumbsSong = new ListCollectionView(thumbsSongList);
            ThumbsArtist = new ListCollectionView(thumbsArtistList);

        }


        private ImageSource _currentCover;
        public ImageSource CurrentCover
        {
            get { return _currentCover; }
            set { _currentCover = value; OnPropertyChanged("CurrentCover"); }
        }


        private bool _allAlbumdSelected;
        public bool AllAlbumSelected
        {
            get { return _allAlbumdSelected; }
            set
            {
                if (value != _allAlbumdSelected)
                {
                    _allAlbumdSelected = value;
                    if (_allAlbumdSelected)
                        DoCmdSelectAll(ThumbsAlbum);
                    else
                        DoCmdSelectNone(ThumbsAlbum);
                    OnPropertyChanged("AllAlbumSelected");
                }
            }
        }

        private bool _allArtistSelected;
        public bool AllArtistSelected
        {
            get { return _allArtistSelected; }
            set
            {
                if (value != _allArtistSelected)
                {
                    _allArtistSelected = value;
                    if (_allArtistSelected)
                        DoCmdSelectAll(ThumbsArtist);
                    else
                        DoCmdSelectNone(ThumbsArtist);
                    OnPropertyChanged("AllArtistSelected");
                }
            }
        }

        private bool _allSongSelected;
        public bool AllSongSelected
        {
            get { return _allSongSelected; }
            set
            {
                if (value != _allSongSelected)
                {
                    _allSongSelected = value;
                    if (_allSongSelected)
                        DoCmdSelectAll(ThumbsSong);
                    else
                        DoCmdSelectNone(ThumbsSong);
                    OnPropertyChanged("AllSongSelected");
                }
            }
        }

        #region Commands

        private RelayCommand _saveListCmd;
        public RelayCommand SaveListCmd
        {
            get
            {
                if (_saveListCmd == null)
                {
                    _saveListCmd = new RelayCommand(param => DoCmdSaveList(), param => {
                        if (NotFoundMp3.Count > 0)
                            return true;
                        return false;
                    });
                 
                }
                return _saveListCmd;
            }
        }


        private RelayCommand _CmdClose;
        public RelayCommand CmdClose
        {
            get
            {
                if (_CmdClose == null)
                {
                    _CmdClose = new RelayCommand(param => DoCmdClose(), param =>
                    {
                        if (!AppModel.IsAppWorking)
                            return true;
                        else
                            return false;
                    });
                }
                return _CmdClose;
            }
        }

        private RelayCommand _CmdApply;
        public RelayCommand CmdApply
        {
            get
            {
                if (_CmdApply == null)
                {
                    _CmdApply = new RelayCommand(param => DoCmdApply(), param => {
                        if (!AppModel.IsAppWorking)
                            return true;
                        else
                            return false;
                    });
                }
                return _CmdApply;
            }
        }     

        #endregion

        #region Do Commands

        //save the list of not found Mp3 in a text file
        private void DoCmdSaveList()
        {           
            FileInfo tempFilename =  new FileInfo(Path.GetTempFileName());
            using (StreamWriter txt = tempFilename.CreateText())
            {
                foreach(Mp3File m in NotFoundMp3){
                    StringBuilder line = new StringBuilder();
                    line.AppendFormat("{0} - {1} ({2}) file: {3}", m.Artist, m.Title, m.AlbumName, m.FileName);
                    txt.WriteLine(line.ToString());
                }

                txt.Flush();
                txt.Close();
            }
            System.Diagnostics.Process.Start("notepad.exe", tempFilename.FullName);           
        }

        private void DoCmdApply()
        {
            //i do remove all not selected covers from the image cache (so the cover will not applied)
            RemoveNotSelectedCovers(ThumbsAlbum);
            RemoveNotSelectedCovers(ThumbsArtist);
            RemoveNotSelectedCovers(ThumbsSong);

            AppModel.ApplyFoundCoversToSongs();
            DoCmdClose();
        }

        private void RemoveNotSelectedCovers(ListCollectionView list)
        { 
          //var notSelectedCover = from t in list
          //                         where !t.IsSelected
          //                         select t;
            var notSelectedCover = new List<CoverThumb>();
            foreach (CoverThumb t in list)
                if (!t.IsSelected)
                    notSelectedCover.Add(t);

           foreach (CoverThumb removingThumb in notSelectedCover)
                this.Covers.RemoveCover(removingThumb.CachedUrl.ToString().ToLowerInvariant());
        }

        private void DoCmdClose()
        {
            OnRequestClose();
        }

        private void DoCmdSelectAll(ListCollectionView list)
        {
            if (list != null)
                foreach (CoverThumb c in list)
                    c.IsSelected = true;        
        }

        private void DoCmdSelectNone(ListCollectionView list)
        {
            if(list != null)
                foreach (CoverThumb c in list)
                    c.IsSelected = false;        
        }

        #endregion

        /// <summary>
        /// Display the cover of the selected song, and change also the previous and next image if exist
        /// </summary>
        /// <param name="selectedCover">current selected item</param>
        public void DisplayCover(CoverThumb selectedCover)
        {
            if (selectedCover != null)
            {
                var preview = AppModel.CoverImageCache[selectedCover.CachedUrl.ToString().ToLowerInvariant()];
                CurrentCover = Shoozla.DataModel.Helper.ImageHelper.ImageToBitmapImage(preview.Cover);
            }
        }

    }
}
